﻿using System;
using System.Web.UI.WebControls;
using System.Text;

namespace FlowersStore
{
	public partial class Search : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
				if (Request.QueryString["keywords"] == null)
					Response.Redirect("default.aspx");
				else
				{
					string[] keywords = Request.QueryString["keywords"].Split();
					SearchDataSource.SelectParameters.Clear();
					if (keywords.Length > 0)
					{
						tbKeyWords.Text = keywords[0];
						SearchDataSource.SelectParameters.Add("keyword1", keywords[0]);
					}
					if (keywords.Length > 1)
					{
						tbKeyWords.Text += " " + keywords[1];
						SearchDataSource.SelectParameters.Add("keyword2", keywords[1]);
					}
					if (keywords.Length > 2)
					{
						tbKeyWords.Text += " " + keywords[2];
						SearchDataSource.SelectParameters.Add("keyword3", keywords[2]);
					}
					if (keywords.Length > 3)
					{
						tbKeyWords.Text += " " + keywords[1];
						SearchDataSource.SelectParameters.Add("keyword4", keywords[3]);
					}
					if (keywords.Length > 4)
					{
						tbKeyWords.Text += " " + keywords[1];
						SearchDataSource.SelectParameters.Add("keyword5", keywords[4]);
					}
					ListView1.DataBind();
					((FlowersStore.SiteMaster)this.Master).FillCartItems();
				}
		}



		protected void btnInCart_Click(object sender, EventArgs e)
		{
			long productId = long.Parse(((ImageButton)sender).CommandArgument);
			if (Session["cart"] == null)
				Session["cart"] = new UserCart();
			UserCart cart = (UserCart)Session["cart"];
			cart.AddPosition(productId, 1);
			((FlowersStore.SiteMaster)this.Master).FillCartItems();
		}

		protected void SearchAgain(object sender, EventArgs e)
		{
			string[] keyWords = tbKeyWords.Text.Split();
			StringBuilder sb = new StringBuilder();
			foreach (string keyWord in keyWords)
				sb.Append(keyWord + "+");
			Response.Redirect("Search.aspx?keywords=" + sb.ToString().TrimEnd('+'));
		}
	}

}